//
//  AppDelegate.m
//  BiZhi
//
//  Created by ryou on 2021/4/9.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "BZWallPaperViewController.h"
#import "BZBellsViewController.h"
#import "BZAboutViewController.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
#import "BUDAnimationTool.h"

@interface AppDelegate ()<BUSplashZoomOutViewDelegate,BUSplashAdDelegate>
@property(nonatomic,strong)BUSplashAdView *bzBUSplashAdView;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    ViewController * view=[[ViewController alloc]init];
    self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController=view;
    [self.window makeKeyAndVisible];
    
    [UMConfigure initWithAppkey:@"607fa4549e4e8b6f617a1cbe" channel:@"ios"];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:kReachabilityChangedNotification object:nil];

    [self reachabilityChanged];
    
    
    return YES;
}

-(void)reachabilityChanged
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status != NotReachable) {

        if (@available(iOS 14, *)) {
            [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self bbzsetupBUAdSDK];

                });

            }];
        } else {
            [self bbzsetupBUAdSDK];
        }
    }

}

-(void)rootView{
    
    UITabBarController *tabVC=[[UITabBarController alloc]init];
    
    UIViewController *view1=[[BZWallPaperViewController alloc]init];
    UINavigationController *navc1=[[UINavigationController alloc]initWithRootViewController:view1];
    view1.title = @"壁纸大全";

    UIViewController *view2=[[BZBellsViewController alloc]init];
    UINavigationController *navc2=[[UINavigationController alloc]initWithRootViewController:view2];
    view2.title = @"指令大全";

    UIViewController *view3=[[BZAboutViewController alloc]init];
    UINavigationController *navc3=[[UINavigationController alloc]initWithRootViewController:view3];
    view3.title = @"关于";

    
    [navc1.tabBarItem setSelectedImage:[[UIImage imageNamed:@"bz_tabbar_icon_3.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    [navc2.tabBarItem setSelectedImage:[[UIImage imageNamed:@"bz_tabbar_icon_1.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    [navc3.tabBarItem setSelectedImage:[[UIImage imageNamed:@"bz_tabbar_icon_2.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

    [navc1.tabBarItem setImage:[[UIImage imageNamed:@"bz_tabbar_icon_3.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    [navc2.tabBarItem setImage:[[UIImage imageNamed:@"bz_tabbar_icon_1.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    [navc3.tabBarItem setImage:[[UIImage imageNamed:@"bz_tabbar_icon_2.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

    
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] =kBZMianColor;

    [navc1.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    [navc2.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    [navc3.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];

    NSMutableDictionary *selectTextAttrs = [NSMutableDictionary dictionary];
    selectTextAttrs[NSForegroundColorAttributeName] = kBZSecondColor;

    [navc1.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];
    [navc2.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];
    [navc3.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];

    [tabVC setViewControllers:@[navc1,navc2,navc3]];
    
    self.window.rootViewController = tabVC;
    [self.window makeKeyAndVisible];
    
}

- (void)bbzsetupBUAdSDK {
    NSInteger territory = [[NSUserDefaults standardUserDefaults]integerForKey:@"territory"];
    BOOL isNoCN = (territory>0&&territory!=BUAdSDKTerritory_CN);
    
    BUAdSDKConfiguration *configuration = [BUAdSDKConfiguration configuration];
    configuration.territory = isNoCN?BUAdSDKTerritory_NO_CN:BUAdSDKTerritory_CN;
    configuration.GDPR = @(0);
    configuration.coppa = @(0);
    configuration.CCPA = @(1);
    configuration.logLevel = BUAdSDKLogLevelVerbose;
    configuration.appID = kbuadAppKey;
    [BUAdSDKManager startWithAsyncCompletionHandler:^(BOOL success, NSError *error) {

        dispatch_async(dispatch_get_main_queue(), ^{
                // splash AD demo
                [self bbbzaddSplashAD];
            });
    }];
    

    
}

#pragma mark - Splash
- (void)bbbzaddSplashAD {
    CGRect frame = [UIScreen mainScreen].bounds;
    self.bzBUSplashAdView = [[BUSplashAdView alloc] initWithSlotID:kbuadSlotId frame:frame];
    // tolerateTimeout = CGFLOAT_MAX , The conversion time to milliseconds will be equal to 0
    self.bzBUSplashAdView.tolerateTimeout = 3;
    // 不支持中途更改代理，中途更改代理会导致接收不到广告相关回调，如若存在中途更改代理场景，需自行处理相关逻辑，确保广告相关回调正常执行。
    self.bzBUSplashAdView.delegate = self;

    UIWindow *keyWindow = self.window;
    [self.bzBUSplashAdView loadAdData];
    [keyWindow.rootViewController.view addSubview:self.bzBUSplashAdView];
    self.bzBUSplashAdView.rootViewController = keyWindow.rootViewController;
}

- (void)removeSplashAdView {
    if (self.bzBUSplashAdView) {
        [self.bzBUSplashAdView removeFromSuperview];
        self.bzBUSplashAdView = nil;
    }
    [self rootView];
}


- (void)splashAdDidLoad:(BUSplashAdView *)splashAd {
    [self pbu_logWithSEL:_cmd msg:[NSString stringWithFormat:@"mediaExt %@",splashAd.mediaExt]];
    if (splashAd.zoomOutView) {
        UIViewController *parentVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        //Add this view to your container
        [parentVC.view insertSubview:splashAd.zoomOutView belowSubview:splashAd];
        splashAd.zoomOutView.rootViewController = parentVC;
        splashAd.zoomOutView.delegate = self;
    }
}

- (void)splashAdDidClose:(BUSplashAdView *)splashAd {
    if (splashAd.zoomOutView) {
        [[BUDAnimationTool sharedInstance] transitionFromView:splashAd toView:splashAd.zoomOutView splashCompletion:^{
            [splashAd removeFromSuperview];
        }];
    } else{
        // Be careful not to say 'self.splashadview = nil' here.
        // Subsequent agent callbacks will not be triggered after the 'splashAdView' is released early.
        [splashAd removeFromSuperview];
    }
    [self pbu_logWithSEL:_cmd msg:@""];
}

- (void)splashAdDidClick:(BUSplashAdView *)splashAd {
    if (splashAd.zoomOutView) {
        [splashAd.zoomOutView removeFromSuperview];
    }
    // Be careful not to say 'self.splashadview = nil' here.
    // Subsequent agent callbacks will not be triggered after the 'splashAdView' is released early.
    [splashAd removeFromSuperview];
    [self pbu_logWithSEL:_cmd msg:@""];
}

- (void)splashAdDidClickSkip:(BUSplashAdView *)splashAd {
    if (splashAd.zoomOutView) {
        [[BUDAnimationTool sharedInstance] transitionFromView:splashAd toView:splashAd.zoomOutView splashCompletion:^{
            [self removeSplashAdView];
        }];
    } else{
        // Click Skip, there is no subsequent operation, completely remove 'splashAdView', avoid memory leak
        [self removeSplashAdView];
    }
    [self pbu_logWithSEL:_cmd msg:@""];
}

- (void)splashAd:(BUSplashAdView *)splashAd didFailWithError:(NSError *)error {
    // Display fails, completely remove 'splashAdView', avoid memory leak
    [self removeSplashAdView];
    [self pbu_logWithSEL:_cmd msg:@""];
}

- (void)splashAdWillVisible:(BUSplashAdView *)splashAd {
    [self pbu_logWithSEL:_cmd msg:@""];
}





- (void)splashAdWillClose:(BUSplashAdView *)splashAd {
    [self pbu_logWithSEL:_cmd msg:@""];
}

- (void)splashAdDidCloseOtherController:(BUSplashAdView *)splashAd interactionType:(BUInteractionType)interactionType {
    // No further action after closing the other Controllers, completely remove the 'splashAdView' and avoid memory leaks
    [self removeSplashAdView];
    
    [self pbu_logWithSEL:_cmd msg:@""];
}



- (void)splashAdCountdownToZero:(BUSplashAdView *)splashAd {
    // When the countdown is over, it is equivalent to clicking Skip to completely remove 'splashAdView' and avoid memory leak
    if (!splashAd.zoomOutView) {
        [self removeSplashAdView];
    }
    [self pbu_logWithSEL:_cmd msg:@""];
}

#pragma mark - BUSplashZoomOutViewDelegate
- (void)splashZoomOutViewAdDidClick:(BUSplashZoomOutView *)splashAd {
    [self pbu_logWithSEL:_cmd msg:@""];
}

- (void)splashZoomOutViewAdDidClose:(BUSplashZoomOutView *)splashAd {
    // Click close, completely remove 'splashAdView', avoid memory leak
    [self removeSplashAdView];
    [self pbu_logWithSEL:_cmd msg:@""];
}

- (void)splashZoomOutViewAdDidAutoDimiss:(BUSplashZoomOutView *)splashAd {
    // Back down at the end of the countdown to completely remove the 'splashAdView' to avoid memory leaks
    [self removeSplashAdView];
    [self pbu_logWithSEL:_cmd msg:@""];
}

- (void)splashZoomOutViewAdDidCloseOtherController:(BUSplashZoomOutView *)splashAd interactionType:(BUInteractionType)interactionType {
    // No further action after closing the other Controllers, completely remove the 'splashAdView' and avoid memory leaks
    [self removeSplashAdView];
    [self pbu_logWithSEL:_cmd msg:@""];
}


- (void)pbu_logWithSEL:(SEL)sel msg:(NSString *)msg {
 
}


-(void)applicationWillEnterForeground:(UIApplication *)application
{
    [self bbbzaddSplashAD];
}
@end
